package cloudPayAdmin.admin.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
import cloudPayAdmin.constant.Constant;
import cloudPayAdmin.util.AliyunUtil;
import cloudPayAdmin.util.HttpUtil;

@Controller
@RequestMapping("/cloudpay/system")
public class SystemController {

	private static Map<String, List<PartETag>> tagMap = new HashMap<String, List<PartETag>>();

	@Autowired
	Environment env;

	/**
	 * 跳转到错误页
	 * 
	 * @return
	 */
	@RequestMapping("/toErrorPage")
	public String toError() {
		return "common/error";
	}

	/**
	 * 跳转到未授权页
	 * 
	 * @return
	 */
	@RequestMapping("/toUnAuthorizationPage")
	public String toUnAuthorization() {
		return "common/unAuthorization";
	}

	@RequestMapping("/exportExcelData")
	public String exportExcelData(HttpServletRequest request) throws FileNotFoundException, IOException {
		String[] headers = StringUtils.splitByWholeSeparator(request.getParameter("header"), "|");
		String[] values = StringUtils.splitByWholeSeparatorPreserveAllTokens(request.getParameter("excelData"), "|");

		Workbook wb = new XSSFWorkbook();
		Sheet sheet = wb.createSheet("sheet1");
		Row firstRow = sheet.createRow(0);

		// 写表头
		for (int i = 0; i < headers.length; i++) {
			Cell cell = firstRow.createCell(i, Cell.CELL_TYPE_STRING);
			cell.setCellValue(headers[i]);
		}

		// 写表格数据
		int rowIndex = 1;
		Row row = null;
		for (int j = 0; j < values.length; j++) {
			// Row row = sheet.createRow(rowIndex);
			if (j % headers.length == 0) {
				row = sheet.createRow(rowIndex);
				rowIndex++;
			}

			Cell cell = row.createCell(j % headers.length, Cell.CELL_TYPE_STRING);
			// 把html换行符转成window的换行符
			String cellValue = values[j];
			int index = StringUtils.lastIndexOfAny(cellValue, new String[] { "<br/>", "<br>", "</br>" });
			if (index >= 0) {
				cellValue = StringUtils.substring(cellValue, 0, index);
			}
			cell.setCellValue(StringUtils.replaceEach(cellValue, new String[] { "<br/>", "<br>", "</br>" },
					new String[] { "\r\n", "\r\n", "\r\n" }));
		}

		String fileName = Constant.EXCEL_FILE_PATH + File.separator + System.currentTimeMillis() + ".xlsx";
		String filePath = env.getProperty("image.upload.base.path") + fileName;

		File file = new File(filePath);
		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		wb.write(new FileOutputStream(file));

		String redirectUrl = env.getProperty("image.http.base.path")
				+ env.getProperty("image.upload.database.suffix.path")
				+ StringUtils.replace(fileName, File.separator, HttpUtil.HTTP_PATH_SEPERATOR);
		return "redirect:" + redirectUrl;
	}

	/**
	 * 阿里云分片上传请求
	 */
	@RequestMapping("/aliyunMultipartUpload")
	@ResponseBody
	public String aliyunMultipartUpload(HttpServletRequest request, MultipartFile file, String name,
			Integer chunk, Integer chunks, String uploadId, String key, String bucketName) {

		if (ServletFileUpload.isMultipartContent(request)) {
			try {

				if (StringUtils.isBlank(uploadId)) {
					OSSClient ossClient = AliyunUtil.getOssClient();

					key = AliyunUtil.generateAliyunKey(Constant.VIDEO_FILE_PATH, name); // 生成路径

					bucketName = AliyunUtil.PUBLIC_BUCKETNAME;
					InitiateMultipartUploadRequest uploadRequest = new InitiateMultipartUploadRequest(bucketName, key);
					InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(uploadRequest);
					uploadId = result.getUploadId();
					List<PartETag> partETags = new ArrayList<PartETag>();
					tagMap.put(uploadId, partETags);
				}

				UploadPartRequest uploadPartRequest = new UploadPartRequest();
				uploadPartRequest.setBucketName(bucketName);
				uploadPartRequest.setKey(key);
				uploadPartRequest.setUploadId(uploadId);
				uploadPartRequest.setInputStream(file.getInputStream());
				uploadPartRequest.setPartSize(file.getSize()); // 1m
				// 设置分片号，范围是1~10000，
				uploadPartRequest.setPartNumber(chunk == null ? 1 : chunk + 1 );
				UploadPartResult uploadPartResult = AliyunUtil.getOssClient().uploadPart(uploadPartRequest);
				PartETag tag = uploadPartResult.getPartETag();
				List<PartETag> partETags = tagMap.get(uploadId);
				partETags.add(tag);
				tagMap.put(uploadId, partETags);

				// 合并文件
				if ((chunk != null && chunk + 1 == chunks) || (chunk == null && chunks == null)) {
					List<PartETag> uploadedPartETags = tagMap.get(uploadId);
					CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
							bucketName, key, uploadId, uploadedPartETags);
					AliyunUtil.getOssClient().completeMultipartUpload(completeMultipartUploadRequest);

					// 合并完成后清空map
					tagMap.remove(uploadId);
				}

				Map<String, Object> m = new HashMap<String, Object>();
				m.put("uploadId", uploadId);
				m.put("key", key);
				m.put("bucketName", bucketName);
				m.put("status", true);
				return JSON.toJSONString(m);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		// 如果不是分片上传请求
		return null;
	}

}
